package org.zjt.rxjava.lession.second;

import io.reactivex.Observable;
import io.reactivex.subjects.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * Description: Subject 差异
 *
 *
 *     类名               功能
 *
 * AsyncSubject       接受 `onComplete()` 之前的最后一个数据
 *
 * BehaviorSubject    订阅之前的最后一个数据，再接收订阅之后发射过来的数据
 *
 * PublishSubject     接受订阅之后的消息
 *
 * ReplaySubject      接受所有发送的消息
 *
 *
 *   <a href="http://reactivex.io/documentation/subject.html">文档</a>
 *
 * @author juntao.zhang
 * Date: 2018-06-20 下午5:40
 * @see
 */
@Slf4j
public class SubjectTest {


    /**
     * onComplete 中的最后一个
     */
    @Test
    public void asyncSubjectTest() {

        AsyncSubject asyncSubject = AsyncSubject.create();
        asyncSubject.onNext(211);
        asyncSubject.onComplete();
        Observable<String> map = asyncSubject.map(String::valueOf);
        map.subscribe(log::info);
        map.subscribe(log::info);


        Observable<String> objectObservable = Observable.create(emitter -> {
            emitter.onNext("222");
            emitter.onNext("www");
            emitter.onComplete();
        });

        objectObservable.subscribe(log::info);
        objectObservable.subscribe(log::info);


    }


    /**
     * 订阅之后的消息
     */
    @Test
    public void publishSubjectTest() {
        PublishSubject<String> objectPublishSubject = PublishSubject.create();
        objectPublishSubject.onNext("2222");
        objectPublishSubject.subscribe(log::info);
        objectPublishSubject.onNext("3333");
        objectPublishSubject.onComplete();
    }

    /**
     * 订阅前一个和订阅之后的全部
     */
    @Test
    public void behaviorSubjectTest() {
        BehaviorSubject<String> behaviorSubject = BehaviorSubject.create();
        behaviorSubject.onNext("111");
        behaviorSubject.onNext("222");

        behaviorSubject.subscribe(log::info);
        behaviorSubject.onNext("333");
        behaviorSubject.onNext("444");

        behaviorSubject.onComplete();
    }


    /**
     * 得到所有的消息
     */
    @Test
    public void replaySubjectTest() {
        ReplaySubject<String> replaySubject = ReplaySubject.create();
        replaySubject.subscribe(log::info);
        replaySubject.onNext("111");
        replaySubject.onNext("222");
        replaySubject.onNext("333");
        replaySubject.subscribe(log::info);
    }




}
